const WebSocket = require('ws');
const express = require('express');
const http = require('http');
const path = require('path');
const config = require('./config/config');
const ChatService = require('./services/ChatService');

class Server {
  constructor() {
    this.app = express();
    this.server = http.createServer(this.app);
    this.wss = new WebSocket.Server({
      server: this.server,
      maxPayload: 100 * 1024 * 1024 // 100MB
    });

    this.chatService = new ChatService(this.wss);
    this.setupExpress();
  }

  setupExpress() {
    // 静态文件服务
    if (config.isPkg) {
      const publicPath = path.resolve(path.dirname(process.pkg.defaultEntrypoint), '../public');
      this.app.use(express.static(publicPath));
      this.app.get('/', (req, res) => {
        res.sendFile(path.join(process.pkg.defaultEntrypoint, '../public/index.html'));
      });
    } else {
      this.app.use(express.static(path.join(__dirname, '../public')));
    }

    // 上传文件访问
    this.app.use('/uploads', express.static(config.UPLOAD_DIR));

    this.app.get('/server-address', async (req, res) => {
      const clientService = this.chatService.clientService;
      const localIP = clientService.getLocalIP();
      const address = localIP ? `http://${localIP}:${config.PORT}` : '无法获取 IP 地址';
      res.json({ address });
    });
  }

  start() {
    this.server.listen(config.PORT, () => {
      console.log(`服务器已启动，监听端口：${config.PORT}`);
    });
  }
}

new Server().start(); 